//
//  GXCycleImages.m
//  16-UICollectionViewCycleImage
//
//  Created by 曹曹 on 16/8/4.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "GXCycleImages.h"
#import "UIImageView+DownloadImage.h"
#define kCollectionViewCellReuse @"cellReuse"
#define kArc4RandomColor [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1]

@interface GXCycleImages () <UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UIImageView *placeholderImageView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation GXCycleImages

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}
// SB中创建控件时走下边的方法(读取本地SB,xib等文件)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    [self createPlaceholderImageView];
    [self createCollectionView];
    [self createPageControl];
}
- (void)createPlaceholderImageView {
    self.placeholderImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_placeholderImageView];
}
- (void)createCollectionView {
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_collectionView];
    [_collectionView registerClass:[GXCycleImagesCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
}

- (void)createPageControl {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    [self addSubview:_pageControl];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imagesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GXCycleImagesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
    cell.imageView.image = _imagesArray[indexPath.row];
    return cell;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _placeholderImageView.frame = self.bounds;
    _placeholderImageView.image = _placeholderImage;
    _flowLayout.itemSize = self.bounds.size;
    _collectionView.frame = self.bounds;
    [_collectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(CGRectGetWidth(self.bounds) / 2, CGRectGetHeight(self.bounds) - 10);
    _pageControl.numberOfPages = _imagesArray.count - 2;
    [_pageControl addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventValueChanged];
}

- (void)changeImage:(UIPageControl *)pageControl {
    _collectionView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds) * (_pageControl.currentPage + 1), 0);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 直接判断与0相等有何问题
    if (scrollView.contentOffset.x == 0) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imagesArray.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x >= _collectionView.bounds.size.width * (_imagesArray.count - 1) - 1) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    NSInteger page = _collectionView.contentOffset.x / self.bounds.size.width;
    _pageControl.currentPage = page - 1;
}

- (void)setImagesArray:(NSMutableArray *)imagesArray {
    _imagesArray = [self imageArrayWithArray:imagesArray];
}

- (__kindof NSArray *)imageArrayWithArray:(NSArray *)array {
    NSMutableArray *imageArray = [NSMutableArray array];
    // 子线程执行下载任务
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (NSString *urlString in array) {
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:data];
            [imageArray addObject:image];
        }
        // 回到主线程.
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *first = [imageArray firstObject];
            UIImage *laast = [imageArray lastObject];
            [imageArray insertObject:laast atIndex:0];
            [imageArray addObject:first];
            _placeholderImageView = nil;
            [self createPageControl];
            [self addTimer];
            [_collectionView reloadData];
        });
    });
    return imageArray;
}

- (void)addTimer {
    _timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(xchImage:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)removeTimer {
    [self.timer invalidate];
    _timer = nil;
}

- (void)xchImage:(NSTimer *)timer {
    int page = (int)self.pageControl.currentPage;
    if (page == _imagesArray.count - 3) {
        page = 0;
    } else {
        page++;
    }
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
//    [self.collectionView setContentOffset:CGPointMake((page + 1) * CGRectGetWidth(self.bounds), 0)];
    _pageControl.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addTimer];
}


@end

/**
 GXCycleImagesCell
 */
@implementation GXCycleImagesCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_imageView];
    }
    return self;
}

@end
